package com.kuangjia.student_ems.security;

import com.kuangjia.student_ems.entity.User;
import com.kuangjia.student_ems.exception.ResourceNotFoundException;
import com.kuangjia.student_ems.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));

        return new CustomUserDetails(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRole().name()))
        );
    }
    
    // 自定义UserDetails实现，包含用户ID
    public static class CustomUserDetails extends org.springframework.security.core.userdetails.User {
        private final Long id;
        
        public CustomUserDetails(Long id, String username, String password, 
                               java.util.Collection<? extends org.springframework.security.core.GrantedAuthority> authorities) {
            super(username, password, authorities);
            this.id = id;
        }
        
        public Long getId() {
            return id;
        }
    }
} 